<template>
  <div>
    <!-- 查询表单 -->
    <el-row>
      <el-col :span="18">
        <div>
          <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="数据表名称">
              <el-input
                clearable
                @keyup.enter.native="listPageData"
                v-model="queryParams.tableName"
                @clear="listPageData"
                placeholder="数据表名称"
                size="small"
              ></el-input>
            </el-form-item>

            <el-form-item label="数据表描述">
              <el-input
                clearable
                @keyup.enter.native="listPageData"
                v-model="queryParams.tableComment"
                @clear="listPageData"
                placeholder="数据表描述"
                size="small"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="mini" icon="el-icon-search" @click="listPageData">搜索</el-button>
            </el-form-item>
            <el-form-item>
              <el-button plain size="mini" icon="el-icon-refresh" @click="refreshParmas">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>

      <el-col :span="3" :offset="3">
        <div>
          <el-button type="primary" plain size="mini" @click="batchGeneratorCode">批量生成代码</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      highlight-current-row
      border
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>

      <el-table-column label="数据表名称" align="center">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="right">
            <p>数据表 {{ scope.row.tableName }} 详细信息</p>
            <p v-html="formatDetail(scope.row.tableDetail)"></p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.tableName }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="数据表描述" prop="tableComment" align="center"> </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
      <el-table-column label="修改时间" prop="updateTime" align="center"></el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" plain size="mini" @click="generatorCode(scope.$index, scope.row)"
            >生成代码</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 生成代码对话框 -->
    <el-dialog title="代码生成选项" :before-close="handleClose" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="生成ControllerApi" :label-width="formLabelWidth">
          <el-switch v-model="form.controllerApi" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Controller" :label-width="formLabelWidth">
          <el-switch v-model="form.controller" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Service" :label-width="formLabelWidth">
          <el-switch v-model="form.service" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成ServiceImpl" :label-width="formLabelWidth">
          <el-switch v-model="form.serviceImpl" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Mapper" :label-width="formLabelWidth">
          <el-switch v-model="form.mapper" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成MapperXml" :label-width="formLabelWidth">
          <el-switch v-model="form.mapperXml" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Entity" :label-width="formLabelWidth">
          <el-switch v-model="form.entity" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Provider" :label-width="formLabelWidth">
          <el-switch v-model="form.provider" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成ProviderImpl" :label-width="formLabelWidth">
          <el-switch v-model="form.providerImpl" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Facade" :label-width="formLabelWidth">
          <el-switch v-model="form.facade" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Dto" :label-width="formLabelWidth">
          <el-switch v-model="form.dto" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Vo" :label-width="formLabelWidth">
          <el-switch v-model="form.vo" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Bo" :label-width="formLabelWidth">
          <el-switch v-model="form.bo" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成Vue" :label-width="formLabelWidth">
          <el-switch v-model="form.vue" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="生成js" :label-width="formLabelWidth">
          <el-switch v-model="form.js" active-text="是" inactive-text="否" class="switch-item"> </el-switch>
        </el-form-item>

        <el-form-item label="作者" prop="author" :label-width="formLabelWidth">
          <el-input clearable placeholder="请输入作者名称" v-model="form.author" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cannelSubmit">取消</el-button>
        <el-button type="primary" plain @click="invertSelection">反选</el-button>
        <el-button type="primary" @click="submitData('ruleForm')">提交</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import { loadPageData, download, getName } from '../api/tables'

export default {
  name: 'Tables',
  data() {
    return {
      // 查询条件
      queryParams: {
        tableName: '',
        tableComment: '',
        pageNum: 1,
        pageSize: 10,
      },
      // 表单内容
      form: {
        controller: true,
        service: true,
        serviceImpl: true,
        mapper: true,
        mapperXml: true,
        entity: true,
        provider: true,
        providerImpl: true,
        facade: true,
        domainApplication: false,
        controllerApi: true,
        dto: true,
        vo: true,
        bo: true,
        vue: true,
        js: true,
        author: '',
        tableNameList: [],
      },

      // 表单校验
      rules: {
        author: [{ required: true, message: '作者名称不能为空', trigger: 'blur' }],
      },

      // 对话框文本内容宽度
      formLabelWidth: '150px',
      // 默认当前页
      currentPage: 1,
      // 默认数据总量
      totalCount: 0,
      // 对话框默认关闭状态
      dialogFormVisible: false,
      // 表格数据
      tableData: [],
    }
  },
  methods: {
    /**
     * 反选
     */
    invertSelection() {
      this.form.controller = !this.form.controller
      this.form.service = !this.form.service
      this.form.serviceImpl = !this.form.serviceImpl
      this.form.mapper = !this.form.mapper
      this.form.mapperXml = !this.form.mapperXml
      this.form.entity = !this.form.entity
      this.form.provider = !this.form.provider
      this.form.providerImpl = !this.form.providerImpl
      this.form.facade = !this.form.facade
      this.form.controllerApi = !this.form.controllerApi
      this.form.dto = !this.form.dto
      this.form.vo = !this.form.vo
      this.form.bo = !this.form.bo
      this.form.vue = !this.form.vue
      this.form.js = !this.form.js
    },

    /**
     * 取消提交
     */
    cannelSubmit() {
      console.log('取消提交')
      // 关闭对话框
      this.dialogFormVisible = false
      // 刷新表单
      this.refreshForm()
    },

    /**
     * 关闭对话框
     */
    handleClose() {
      this.cannelSubmit()
    },

    /**
     * 格式化详情信息
     */
    formatDetail(detail) {
      // console.log(detail)
      // 手动反转义
      const unescapedDetial = detail.replace(/\\n/g, '\n')
      // 替换 \n 为 <br>
      var detailInfo = unescapedDetial.replace(/\n/g, '<br>')
      return detailInfo
    },

    /**
     * 重置查询条件
     */
    refreshParmas() {
      this.queryParams.tableName = ''
      this.queryParams.tableComment = ''
      this.listPageData()
    },

    /**
     * 查询页面数据
     */
    listPageData() {
      console.log('加载数据')
      loadPageData(this.queryParams).then((res) => {
        this.tableData = res.data.pageData
        this.totalCount = res.data.totalCount
      })
    },

    /**
     * 单个生成代码
     */
    generatorCode(index, row) {
      // console.log(index, row)
      console.log('单个生成代码')
      // this.form.tableNameList = row.tableName
      this.form.tableNameList.push(row.tableName)
      console.log(this.form.tableNameList)

      // 开启代码生成对话框
      this.openOrCloseGeneratorView()
    },

    /**
     * 提交代码生成
     */
    submitData(formName) {
      console.log('提交代码生成')
      // 校验必填项
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('提交生成代码请求')
          // 生成代码
          this.generator()
        } else {
          console.log('error submit!!')
        }
      })
    },

    /**
     * 生成代码
     */
    generator() {
      console.log('请求后端接口生成代码')
      console.log('作者名称' + this.form.author)

      // 请求后端接口下载代码压缩包
      download(this.form)
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', 'generatedcode.zip')
          document.body.appendChild(link)
          link.click()

          // 关闭对话框
          this.openOrCloseGeneratorView()
          // 刷新重置form提交内容
          this.refreshForm()
        })
        .catch((error) => {
          console.error('下载代码失败：', error)
        })
    },

    /**
     * 刷新重置form提交内容
     */
    refreshForm() {
      console.log('刷新重置form提交内容')
      this.form.controller = true
      this.form.service = true
      this.form.serviceImpl = true
      this.form.mapper = true
      this.form.mapperXml = true
      this.form.entity = true
      this.form.provider = true
      this.form.providerImpl = true
      this.form.facade = true
      this.form.domainApplication = false
      this.form.controllerApi = true
      this.form.dto = true
      this.form.vo = true
      this.form.bo = true
      this.form.vue = true
      this.form.js = true
      this.form.author = ''
      // 清空选中的数据表
      this.form.tableNameList = []
      // 刷新页面数据
      this.listPageData()
    },

    /**
     * 提示错误消息
     */
    errorMessage(message) {
      this.$message.error(message)
    },

    /**
     * 批量生成代码
     */
    batchGeneratorCode() {
      console.log('批量生成代码')
      var temp = this.form.tableNameList
      console.log(temp)
      console.log('批量生成代码数据:' + this.form.tableNameList)

      if (this.form.tableNameList === null || this.form.tableNameList.length == 0) {
        this.errorMessage('未选中任何数据')
      } else {
        // 开启对话框
        this.openOrCloseGeneratorView()
      }
    },

    /**
     * 开启或关闭代码生成对话框
     */
    openOrCloseGeneratorView() {
      this.dialogFormVisible = !this.dialogFormVisible
    },

    /**
     * 表格多选操作
     */
    handleSelectionChange(selection) {
      var temp = selection.map((item) => item.tableName)
      console.log('选中数据' + temp)
      this.form.tableNameList = temp
    },

    /**
     * 切换页面数据量
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.pageSize = val
      this.listPageData()
    },

    /**
     * 切换页面
     */
    handleCurrentChange(val) {
      console.log(`当前页 ${val} `)
      // 页码赋值
      this.queryParams.pageNum = val
      // 查询数据
      this.listPageData()
    },

    /**
     * 获取服务名称
     */
    getApplicationName() {
      getName(this.queryParams).then((res) => {
        const applicationName = res.data == null ? 'generator' : res.data
        console.log('服务名称:', applicationName)
        document.title = applicationName
      })
    },
  },

  /**
   * 钩子函数
   */
  created() {
    this.getApplicationName()
    this.listPageData()
  },
}
</script>

<style>
.el-row {
  text-align: left;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 15px;
}
.switch-item {
  float: left;
  margin: 10px 0px;
}
</style>
